package jok.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

	public static void main(String[] args) {

		ServerSocket ss = null;
		BufferedReader br = null;
		try {
			// 申明服务端Socket
			ss = new ServerSocket(10001);
			System.out.println("服务端已启动...");
			// 监听接收
			Socket s = ss.accept();
			// 获得输入流
			InputStream os = s.getInputStream();
			// 获得客户端的IP地址
			InetAddress ia = s.getInetAddress();
			// 输入字节流转换为字符流用于输出
			br = new BufferedReader(new InputStreamReader(os));
			// 持续监听接收
			while (true) {
				String line = null;
				if ((line = br.readLine()) != null) {
					System.out.println(ia + "：" + line);
				}
				// 定义退出
				if ("exit".equals(line)) {
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (ss != null)
					ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
